package com.crm.action;

import java.util.Collection;
import java.util.ArrayList;
import java.util.Map;
import java.lang.reflect.Array;

/**
 * @author <a href="mailto:huang0510@hotmail.com">HuangHuang</a>
 * @version 1.0
 */
public class JSONArray {

    private ArrayList myArrayList;

    public JSONArray() {
        this.myArrayList = new ArrayList();
    }

    public JSONArray(Collection collection) {
        this.myArrayList = (collection == null) ?
            new ArrayList() :
            new ArrayList(collection);
    }

    public JSONArray(Object array) throws Exception{
        this();
        if (array.getClass().isArray()) {
            int length = Array.getLength(array);
            for (int i = 0; i < length; i += 1) {
                this.put(Array.get(array, i));
            }
        } else {
            throw new Exception("JSONArray initial value should be string or collection or array.");
        }
    }

    public JSONArray put(boolean value) {
        put(value ? Boolean.TRUE : Boolean.FALSE);
        return this;
    }

    public JSONArray put(Collection value) {
        put(new JSONArray(value));
        return this;
    }

    public JSONArray put(double value) throws Exception{
        Double d = new Double(value);
        JSONObject.testValidity(d);
        put(d);
        return this;
    }

    public JSONArray put(int value) {
        put(new Integer(value));
        return this;
    }

    public JSONArray put(long value) {
        put(new Long(value));
        return this;
    }

    public JSONArray put(Map value) {
        put(new JSONObject(value));
        return this;
    }

    public JSONArray put(Object value) {
        this.myArrayList.add(value);
        return this;
    }

}

